package com.cn.medicalcare.service.serviceimpl;

import com.cn.medicalcare.customtool.IOTool;
import com.cn.medicalcare.service.UpLoadImgService;

import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

public class UpLoadImgServiceImpl implements UpLoadImgService {

    //静态内部类单例模式
    private static class SingletonClassInstance {
        private static final UpLoadImgServiceImpl instance = new UpLoadImgServiceImpl();
    }

    private UpLoadImgServiceImpl() {
    }

    public static UpLoadImgServiceImpl getInstance() {
        return UpLoadImgServiceImpl.SingletonClassInstance.instance;
    }

    @Override
    public String upLoadImg(Part part) {
        File file = null;
        try {
            String disposition = part.getHeader("Content-Disposition");
            //获取文件类型
            String suffix = disposition.substring(disposition.lastIndexOf("."), disposition.length() - 1);
            LocalDateTime localDateTime = LocalDateTime.now();
            String filepath = localDateTime.getYear() + "/" + localDateTime.getMonthValue() + "/" + localDateTime.getDayOfMonth();
            String filename = (new Date().getTime()-UpLoadImgService.NAMETIME) + suffix;
            String filepathandpath = filepath + "/" + filename;
            InputStream is = part.getInputStream();
            file = new File(DOMAINPATH + "/" + filepath);
            if (!file.exists())
                file.mkdirs();
            FileOutputStream fos;
            fos = new FileOutputStream(DOMAINPATH + "/" + filepathandpath);
            IOTool.BufferIO(is, fos);
            return filepathandpath;
        } catch (Exception e) {
            if (file != null && file.exists() && file.isFile())
                file.delete();
        }
        return null;
    }

    @Override
    public boolean deleteImgByPath(String path) {
        try {
            File file = new File(DOMAINPATH +"/"+ path);
            if (file.exists() && file.isFile()) {
                file.delete();
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }
}
